package com.luoran.bartalks.api;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.action.vo.ScanMaterielResultVo;
import com.luoran.bartalks.annotation.OperationLog;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtMateriel;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPosition;
import com.luoran.bartalks.entity.biz.BtRuleRecord;
import com.luoran.bartalks.service.IBtMaterielService;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPositionService;
import com.luoran.bartalks.service.IBtRuleRecordService;
import com.luoran.bartalks.utils.EnumOperationType;
import com.luoran.bartalks.utils.MapGeoUtil;
import com.luoran.bartalks.utils.UUID;

@RestController
@RequestMapping("/api/ruleRecord")
public class RuleRecordApi {

	@Autowired
	private IBtRuleRecordService ruleRecordService;

	@Autowired
	private IBtPositionService positionService;

	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;

	@Autowired
	private IBtMaterielService materielService;

	@Value("${image.path}")
	private String imagePath;

	@Value("${image.url}")
	private String imageUrl;

	private static final Logger log = LoggerFactory.getLogger(RuleRecordApi.class);

	/**
	 * 打尺功能,点击扫描获取物料信息.
	 * 
	 * @param qrcode
	 * @return
	 */
	@RequestMapping("/scanMateriel")
	public String getscanMaterielResult(String qrcodeStr) {
		JSONObject res = new JSONObject();
		JSONObject data = new JSONObject();
		log.info("识别到的二维码信息[{}]", qrcodeStr);
		if (StringUtils.isEmpty(qrcodeStr)) {
			res.put("state", false);
			res.put("msg", "请重新扫描二维码");
			return res.toJSONString();
		}
		try {
			// 根据箱单物料关系记录id查询
			BtPackingListMateriel packingListMateriel = packingListMaterielService
					.getItemByMaterielQrcodeAndCompanyId(qrcodeStr, AppUser.get().getCompanyId());
			if (packingListMateriel != null) {
				String packingListMaterielId = packingListMateriel.getId();// 获取箱单物料关系id.
				log.info("获取物料箱单记录成功");
				String materielId = packingListMateriel.getMaterielId();
				log.info("获取扫描结果信息");
				ScanMaterielResultVo scanMaterielResult = packingListMaterielService
						.getScanMaterielResult(packingListMaterielId, AppUser.get().getCompanyId());
				if (scanMaterielResult != null) {
					data.put("materielId", materielId);
					data.put("companyName", scanMaterielResult.getCompanyName());
					data.put("projectName", scanMaterielResult.getProjectName());
					data.put("planCode", scanMaterielResult.getPlanCode());
					data.put("planDesc", scanMaterielResult.getPlanDesc());
					data.put("materielCode", scanMaterielResult.getMaterielCode());
					data.put("materielName", scanMaterielResult.getMaterielName());
					data.put("materielEmptyWeight", scanMaterielResult.getEmptyWeight());
					data.put("materielGrossWeight", scanMaterielResult.getGrossWeight());
					data.put("materielLength", scanMaterielResult.getLength());
					data.put("materielWidth", scanMaterielResult.getWidth());
					data.put("materielHeight", scanMaterielResult.getHeight());
					data.put("packingListCode", scanMaterielResult.getPackingListCode());
				} else {
					res.put("state", false);
					res.put("msg", "未找到记录");
					return res.toJSONString();
				}
			} else {
				res.put("state", false);
				res.put("msg", "未找到记录");
				return res.toJSONString();
			}
			res.put("state", true);
			res.put("data", data);
			return res.toJSONString();
		} catch (Exception e) {
			e.printStackTrace();
			res.put("state", false);
			res.put("msg", "系统异常");
			return res.toJSONString();
		}
	}

	@RequestMapping("/savePhoto")
	@OperationLog(EnumOperationType.PHOTOGRAPH)
	public String savePhoto(HttpServletRequest req) {
		JSONObject res = new JSONObject();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		Iterator<String> fileNames = multipartRequest.getFileNames();
		if (!fileNames.hasNext()) {
			res.put("state", false);
			res.put("msg", "请先拍照再上传");
			return res.toJSONString();
		}
		MultipartFile file = multipartRequest.getFile(fileNames.next());// 获取文件 流对象
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();// 获取后缀
		String newName = UUID.get() + suffix;// 新名字
		String deposition = imagePath + "/" + newName;
		String picUrl = imageUrl + "/" + newName;
		try {
			File targetFile = new File(imagePath);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(new File(deposition));
			fos.write(file.getBytes());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			res.put("state", false);
			res.put("msg", "系统异常");
			return res.toJSONString();
		}
		res.put("state", true);
		res.put("msg", "图片上传成功");
		res.put("url", picUrl);
		return res.toJSONString();
	}

	/**
	 * 保存打尺记录
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/saveRecord")
	@OperationLog(EnumOperationType.RULE)
	public String saveRecord(HttpServletRequest req) {
		JSONObject res = new JSONObject();
		log.info("接受APP请求参数>>>");
		try {
			String qrcode = req.getParameter("qrcode");// 二维码
			BigDecimal latitude = new BigDecimal(req.getParameter("latitude"));// 纬度
			BigDecimal longitude = new BigDecimal(req.getParameter("longitude"));// 经度
			String positionId = req.getParameter("positionId");// 位置表id
			String resourceId = req.getParameter("resourceId");// id
			String resourceName = req.getParameter("resourceName");// 名称
			String resourceCode = req.getParameter("resourceCode");// 编码
			BigDecimal length = new BigDecimal(req.getParameter("length"));// 长
			BigDecimal width = new BigDecimal(req.getParameter("width"));// 宽
			BigDecimal height = new BigDecimal(req.getParameter("height"));// 高
			BigDecimal weight = new BigDecimal(req.getParameter("weight"));// 重
			String description = req.getParameter("description");// 备注,描述
			String picUrl = req.getParameter("picUrl");// 图片URL
			// 根据二维码,获取物料信息.
			BtPackingListMateriel PackingListMateriel = packingListMaterielService
					.getItemByMaterielQrcodeAndCompanyId(qrcode, AppUser.get().getCompanyId());
			BtMateriel materiel = materielService.getBtMateriel(PackingListMateriel.getMaterielId());
			// 计算长宽高重量的误差
			BigDecimal lengthError = length.subtract(materiel.getLength()).abs().multiply(materiel.getLength())
					.setScale(2, BigDecimal.ROUND_HALF_UP);
			BigDecimal widthError = width.subtract(materiel.getWidth()).abs().multiply(materiel.getWidth()).setScale(2,
					BigDecimal.ROUND_HALF_UP);
			BigDecimal heightError = height.subtract(materiel.getHeight()).abs().multiply(materiel.getHeight())
					.setScale(2, BigDecimal.ROUND_HALF_UP);
			BigDecimal weightError = weight.subtract(materiel.getEmptyWeight()).abs()
					.multiply(materiel.getEmptyWeight()).setScale(2, BigDecimal.ROUND_HALF_UP);
			BigDecimal standardError = new BigDecimal("0.05");// 误差允许值
			if ("".equals(picUrl)) {// 当前没有拍照,需要判断尺寸误差
				//如果为强制拍照则必须拍照
				if(PackingListMateriel.getTakePhoto()==0) {
					res.put("state", false);
					res.put("msg", "货物有强制拍照属性，请先拍照上传！");
					return res.toJSONString();
				}
				if (lengthError.compareTo(standardError) == 1) {
					res.put("state", false);
					res.put("msg", "长度超出5%的允许范围,请拍照上传");
					return res.toJSONString();
				}
				if (widthError.compareTo(standardError) == 1) {
					res.put("state", false);
					res.put("msg", "宽度超出5%的允许范围,请拍照并上传");
					return res.toJSONString();
				}
				if (heightError.compareTo(standardError) == 1) {
					res.put("state", false);
					res.put("msg", "高度超出5%的允许范围,请拍照并上传");
					return res.toJSONString();
				}
				if (weightError.compareTo(standardError) == 1) {
					res.put("state", false);
					res.put("msg", "重量超出5%的允许范围,请拍照并上传");
					return res.toJSONString();
				}
			}
			// 打尺记录对象
			BtRuleRecord ruleRecord = new BtRuleRecord();
			// 打尺位置信息,根据positionId查询
			BtPosition position = positionService.getPositionById(positionId);
			if (position != null) {
				log.info("从维护地理位置信息中获取当前地点id,名称");
				ruleRecord.setPositionId(position.getId());
				ruleRecord.setPositionName(position.getPositionName());
			} else {
				log.info("当前点为非维护地点,需通过百度地图API获取位置名称");
				ruleRecord.setPositionId("0");
				ruleRecord.setPositionName(
						MapGeoUtil.getAddress(req.getParameter("longitude"), req.getParameter("latitude")));
			}
			ruleRecord.setLatitude(latitude);
			ruleRecord.setLongitude(longitude);
			ruleRecord.setResourceId(resourceId);
			ruleRecord.setResourceName(resourceName);
			ruleRecord.setResourceCode(resourceCode);
			ruleRecord.setPackingListMaterielId(PackingListMateriel.getId());
			ruleRecord.setLength(length);
			ruleRecord.setWidth(width);
			ruleRecord.setHeight(height);
			ruleRecord.setWeight(weight);
			ruleRecord.setDescription(description);
			ruleRecord.setOperatorId(AppUser.get().getId());
			ruleRecord.setCompanyId(AppUser.get().getCompanyId());
			ruleRecord.setOperator(AppUser.get().getAlias());
			ruleRecord.setRuleDate(new Date());
			if (lengthError.compareTo(standardError) == 1 || widthError.compareTo(standardError) == 1
					|| heightError.compareTo(standardError) == 1 || weightError.compareTo(standardError) == 1) {
				ruleRecord.setIsException("1");// 误差超出允许范围,设置打尺异常
			} else {
				ruleRecord.setIsException("0");
			}
			ruleRecordService.saveRecord(ruleRecord, picUrl);
			res.put("state", true);
			res.put("msg", "保存成功");
			return res.toJSONString();
		} catch (Exception e) {
			e.printStackTrace();
			res.put("state", false);
			res.put("msg", "系统异常,保存失败!");
			return res.toJSONString();
		}
	}

}
